package com.alon.spring01.controller;

import com.alon.spring01.common.config.redis.RedisUtil;
import com.alon.spring01.common.exception.MyException;
import com.alon.spring01.common.jwt.JwtHelper;
import com.alon.spring01.common.model.Result;
import com.alon.spring01.concurrent.Singleton;
import com.alon.spring01.concurrent.SingletonEnum;
import com.alon.spring01.mapper.UserMapper;
import com.alon.spring01.model.User;
import com.alon.spring01.model.dto.UserDto;
import com.alon.spring01.utils.HttpClientUtils;
import com.alon.spring01.utils.ResultUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.Collectors;

/**
 * @program: spring01
 * @description: user 控制器
 * @author: yulongguang
 * @create: 2019-04-07 16:16
 **/
@RestController
@Slf4j
@RequestMapping("/user")
@Validated
public class UserController {

    /**
     * 核心线程 8 最大线程 20 保活时间30s 存储队列 10 有守护线程 拒绝策略:将超负荷任务回退到调用者
     */
    private static ExecutorService executor = new ThreadPoolExecutor(8, 20,
            30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10),
            new ThreadFactoryBuilder().setNameFormat("User_Async_FutureTask-%d").setDaemon(true).build(),
            new ThreadPoolExecutor.CallerRunsPolicy());

    private static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
    private static ExecutorService executorService = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());



    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @GetMapping("/getUser")
    public Result<?> getUser(){
        Assert.notNull("","");
        Singleton singleton=Singleton.getInstance();
        Singleton singleton1=Singleton.getInstance1();
        SingletonEnum.INSTANCE.whateverMethod();
        log.info("singleton:{}",singleton);
        LongAdder longAdder=new LongAdder();
        AtomicLong atomicLong=new AtomicLong();
        atomicLong.addAndGet(1);
        longAdder.add(1);
        int[] str={1,2,3};
        String key = "test123";
//        boolean acquire = DistributedRedisLock.acquire(key);
//        log.info("acquire{}",acquire);
        return ResultUtil.ok(userMapper.selectAll());
    }
    @Scheduled(cron = "00 50 18 19 08 ?")
    public Result<?> reader(){
        //1:http://localhost:9020/user/getUser
        String exchange = HttpClientUtils.exchangeAndPost("http://localhost:9020/country/insert");
        log.info("exchange:{}",exchange);
//        ResponseEntity<String> forEntity = restTemplate
//                .getForEntity("http://localhost:9020/user/getUser", String.class);
//
//        String body = forEntity.getBody();
        //返回结果
//        List<User> users = Optional.ofNullable(exchange).map(b -> JSON
//                .parseObject(b, new TypeReference<Result<List<User>>>() {
//                })).map(Result::getData).orElse(new ArrayList<>());
        //2:http://localhost:9020/insurance/selectByPage?page=2000&pageSize=4000 带参数
//        Map<String, String> map = new HashMap<>();
//        HttpHeaders headers = new HttpHeaders();
//        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
//        map.put("page", "1");
//        map.put("pageSize", "10");
//        String url="http://localhost:9020/country/selectByPage?page={page}&pageSize={pageSize}";
////        String s = HttpClientUtils.doGet(url, map);
//        String exchange = HttpClientUtils.exchange(url, map);
////        ResponseEntity<String> forEntity = restTemplate
////                .getForEntity("http://localhost:9020/country/selectByPage?page={page}&pageSize={pageSize}",
////                        String.class, map);
//        PageInfo<Country> countryPageInfo = Optional.ofNullable(exchange)
//                                                    .map(b -> JSON.parseObject(b,
//                                                            new TypeReference<Result<PageInfo<Country>>>() {
//                                                            })).map(Result::getData)
//                                                    .orElse(new PageInfo<>());
//        System.out.println("countryPageInfo" + countryPageInfo);

        return ResultUtil.ok();
//        return result.getData();
    }
    @GetMapping("/download")
    public void download() {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        String url = "https://yx-perfect.oss-cn-shenzhen.aliyuncs.com/crm_upload/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20190112201229_rs9TRkS.jpg";
        ResponseEntity<byte[]> response = restTemplate.exchange("https://img-blog.csdn.net/20161109183525859", HttpMethod.GET,
                httpEntity, byte[].class);
        log.info("===状态码================");
        log.info(">> {}", response.getStatusCodeValue());
        log.info("===返回信息================");
        log.info(">> {}", response.getHeaders().getContentType());
        log.info(">> {}", response.getHeaders().getContentType().getSubtype());
        try {
            File file = File.createTempFile("ess-",
                    "." + response.getHeaders().getContentType().getSubtype());
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(response.getBody());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @GetMapping(value = "/test01")
    public void Test01() {
        throw new MyException("1001","empty","","获取用户名为空");
    }
    @GetMapping("/getUserList")
    public Result<?> getUserList(){
       Map<String,String> map=new ConcurrentHashMap<>();
        String name = "1,2";
        int[] objects = Arrays.stream(name.split(",")).mapToInt(s->Integer.valueOf(s)).toArray();
        List<User> userList = userMapper.findByParams(objects);
        List<String> strings = userList.stream().map(User::getUserName).collect(Collectors.toList());
        return ResultUtil.ok(strings);
    }

    @GetMapping("/getFetureResult")
    public Result<?> getFetureResult() throws Exception{
//        Future<? extends Result<?>> submit = executorService.submit(this::getUser);
//        Future<? extends Result<?>> submit1 = executorService.submit(this::getUserList);

        Future<? extends Result<?>> submit2 = threadPoolTaskExecutor.submit(this::getUserList);
//        Result<?> result = submit.get();
        Result<?> result1 = submit2.get();
        RedisUtil.set("data", result1.getData(), 2 * 60);

        return ResultUtil.ok(result1.getData());
    }

    @GetMapping("/getToken")
    public Result<?> getToken(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        String header = request.getHeader("User-Agent");

        String generateJWT = JwtHelper.generateJWT("6000", "红冲",header);
        return ResultUtil.ok(generateJWT);
    }

    /**
     * 测试校验
     * @param dto
     * @return
     */
    @PostMapping("/testViolator")
    public Result<?> testViolator(@RequestBody @Valid UserDto dto) {
        long expire = RedisUtil.getExpire("data");

        return ResultUtil.ok(expire);

    }
    @GetMapping("/testViolator02")
    public Result<?> testViolator02( @ApiParam @NotBlank(message = "用户名不能为空") String name){
        return ResultUtil.ok();
    }

    public static void main(String[] args) {
//        MailAccount mailAccount = new MailAccount();
//        mailAccount.setPort(465);//设置邮箱端口号
//        mailAccount.setHost("smtp.163.com");//邮箱SMTP的主机名
//        mailAccount.setUser("abner138@163.com");//发送人
//        mailAccount.setFrom("abner138@163.com");//发送者 必须和USER一致
//        mailAccount.setPass("av123456");//授权码
//        mailAccount.setDebug(true);//是否开启Debug
//        mailAccount.setSslEnable(true);//是否是SSL发送
//        mailAccount.isAuth();
//        Mail mail = new Mail(mailAccount);
//        mail.setHtml(true).setTitle("你1321231231231好").to("1147352218@qq.com").setContent("hello，worl131312313131313131d");
//        mail.send();


//        MailAccount mailAccount = new MailAccount();
//        mailAccount.setPort(465);//设置邮箱端口号
//        mailAccount.setHost("smtp.163.com");//邮箱SMTP的主机名
//        mailAccount.setUser("abner138@163.com");//发送人
//        mailAccount.setFrom("abner138@163.com");//发送者 必须和USER一致
//        mailAccount.setPass("av123456");//授权码
//        mailAccount.setDebug(true);//是否开启Debug
//        mailAccount.setSslEnable(true);//是否是SSL发送
//        mailAccount.isAuth();
//        // Mail mail = new Mail(mailAccount);
//        //mail.setHtml(true).setTitle("你好").to("abner138@163.com").setContent("hello，world");
//        //mail.send();
//        MailUtil.send(mailAccount, CollUtil.newArrayList("1147352218@qq.com"),
//                "这不是垃圾邮箱，这是测试", "邮件来自Hutool测试啊啊奥德赛阿达无法", false);

//        MailUtil.sendHtml( CollUtil.newArrayList("1147352218@qq.com"),
//                "这不是垃圾邮箱，这是测试", "邮件来自Hutool测试啊啊奥德赛阿达无法");

//        ClassPathResource resource = new ClassPathResource("mail.properties");
//        Properties properties = new Properties();
//        try {
//            properties.load(resource.getStream());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String host = properties.getProperty("host");
//        System.out.println(host+"port :"+properties.getProperty("port") +"from :"+properties.getProperty("from"));
//        Console.log("Properties: {}", properties);

//        //读取classpath下的config目录下的XXX.setting，不使用变量
//        Setting setting = new Setting("config/mail.setting");
//        Console.log("setting"+setting);
        //RSA公钥文件路径（百行提供公钥文件）


    }
}
